﻿/*Summary Of The Structure of The Class of SportsView:
 * Part1. Serializable text files -- relate to the part12, for using XML to load a user's data set
 * Part2. Setup references -- creating all references for indexes, stores and items
 * Part3. Constructor
 * Part4. Load and initialize -- SportView Loading codes
 *      Part4.1. Initialize the status of "Menu bar" -- codes for the top menu bar
 *      Part4.2. Load images for "Sport Items" tab -- codes for the 1nd tab
 * Part5. "Home" tab -- codes for the 1st tab
 * Part6. "Sport Items" tab --  codes for the 2nd tab
 * Part7. "Customer " tab -- codes for the 3rd tab
 * Part8. "Customer Activity" tab -- codes for the 4th tab
 * Part9. "Monthly Activity" tab -- codes for the 5th tab
 * Part10. Top Menu Bar -- codes for the top menu bar
 * Part11. Reload codes -- for reloading items of sports, customers, activities, monthly activities
 * Part12. Load Data set from Xml files -- when a user login, load the xml file of the user 
 *                                                             and reload and update data in sports, 
 *                                                             customers, activities and monthly activities  
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization; /* for XML serialization */
using System.IO;
using System.Collections;

namespace AcmeSportsStore
{
    public partial class SportsView : Form
    {
        //*==========Part1. Serializable text files============*//
        /*
         * <code remarks="the following is the type fields of which 
         *  store the information about the configuration file, the data 
         *  to be seralized to the configuration file, and any other data 
         *  that is related to it; to make the type serializable, it must be 
         *  declared public and qualified by a 'Serializable' attribute ">
         */

        [Serializable()]
        public struct DataFilesInfo
        {
            /*Fields reference to text files*/
            public string SportsItemsFile;
            public string CustomersFile;
            public string PurchasedItemsFile;

            /*
             * xml-serializable types need to have a parameterless constructor
             * however all structs already have such a constructor by default
             * and it cannot be explicitly declared
             */

            public DataFilesInfo(string sportsItemsFile, string customersFile, 
                string purchasedItemsFile)
            {
                /*Locate the file's address*/
                SportsItemsFile = sportsItemsFile;
                CustomersFile = customersFile;
                PurchasedItemsFile = purchasedItemsFile;
            }
        }

        /* Different ways supported by sports items store for items to be ordered by */
        private enum SportsItemsOrder
        {
            ById = 0,
            ByName,
            ByDescription,
            ByPrice
        }

        /* different ways supported by customers (list) for customers to be ordered by */
        private enum CustomersOrder
        {
            ById = 0,
            ByName,
            ByAddress,
            ByPhone
        }

        //*=========Part 2. Setup the References=========== *//
        /*
         * An instance of DataFilesInfo type for storing data files information for current user
         */
        private DataFilesInfo mDataFilesInfo;
        private LayoutController mLayoutController = null;

        /*
         * two dialogs related to login and password setting
         */
        private PasswordView passwordForm;
        private NewPasswordView newPasswordForm;

        /*
         * bitmap of image as a default preview of items without a preview image
         */
        private Bitmap mDefSportsItemPreview; 
      
        /*
         * <code remarks = "indexed data">
         * Main refrerences, the three references below connect to 
         * all indexes and all items
         */
        SportsStore mSportsStore = new SportsStore();
        Customers mCustomers = new Customers();
        PurchasedStore mPurchasedStore = new PurchasedStore();
     
        /*
       * current sorting fields for sportsitems and customers
       */
        private SportsItemsOrder mSportsItemsOrder;
        private CustomersOrder mCustomersOrder;

        /*
         * Dictionary for mapping from name of item to preview image of the item if available
         */
        Dictionary<string, Image> mImageDictionary = new Dictionary<string, Image>();

        /*
         * Avoid unnecessary mapping in selections
         */
        bool mNoSelectBack = false;

        //* =============Part3. Constructor ===============*//
       
        public SportsView()
        {
            InitializeComponent();
        }

        //*=============Part4. Loading =================*//
        private void SportsView_Load(object sender, EventArgs e)
        {
            /*
             *Loading window forms and the controller of the window forms
             */
            mLayoutController = new LayoutController(this.tabctlMain);
            passwordForm = new PasswordView();
            newPasswordForm = new NewPasswordView();

            /*
             * <code comments = "setup the file dialogs">
             */
            /*
             * we need to have the dialog prompt the user when it's about
             * to overwrite an existing file.
             */
            SaveFileDlg.OverwritePrompt = true;

            /*
             * the dialog box adds a "xml" as default extention when user
             * doesn't specify it.
             */
            SaveFileDlg.DefaultExt = "xml";
            SaveFileDlg.AddExtension = true;
            /*
             * we have to put a vertical bar at the end
             */
            SaveFileDlg.Filter = "XML Files(*.xml)|*.xml";
            OpenFileDlg.Filter = "XML Files(*.xml)|*.xml";
            /*
             * <code remarks = "default values for fields in the data files pack;
             *  by default the program uses relative paths for these files (
             *  relative to where the project file is located">
             */

            // currently there are no default project settings

            //*============= Initialize the status of "Menu bar" ===============*//
            /*
             * set log status to Logoff
             */
            SetToLogoffState();

              //*=============Part4.2. Load Images for "SportItems" tab============*//
            /*
             *  initialize the default images for preview to the "SportItems" tab
             */
            InitializeImages();
        }

      
        private void InitializeImages()
        {
            mDefSportsItemPreview = new Bitmap(pbxPreview.Width, pbxPreview.Height);
            using (Graphics graphic = Graphics.FromImage(mDefSportsItemPreview))
            {
                string text = "No Image Available";
                Font font = new Font("Arial", 12);
                
                float width = mDefSportsItemPreview.Width;
                float height = mDefSportsItemPreview.Height;

                /*
                 * calculate the best position where the text is displayed
                 */

                graphic.FillRectangle(Brushes.White, new Rectangle
                    (0, 0, pbxPreview.Width, pbxPreview.Height));
                SizeF size = graphic.MeasureString(text, font);

                float left = (width - size.Width) * 0.5f;
                float top = (height - size.Height) * 0.5f;
                
                graphic.DrawString("No Image Available",
                    font, Brushes.Gray, new PointF(left, top));
            }
            mImageDictionary.Clear();
            // images are loaded from the resource
            // use dictionary for mapping from product name to preview image
            mImageDictionary.Add("Basket ball", AcmeSportsStore.Properties.Resources.M0001_basketball);
            mImageDictionary.Add("Net ball", AcmeSportsStore.Properties.Resources.M0002_netball);
            mImageDictionary.Add("Soccer ball", AcmeSportsStore.Properties.Resources.M0003_soccer);
            mImageDictionary.Add("Boxing gloves", AcmeSportsStore.Properties.Resources.M0004_boxingGloves);
            mImageDictionary.Add("Boxing mitts", AcmeSportsStore.Properties.Resources.M0005_boxMitts);
            mImageDictionary.Add("Cycling helmet", AcmeSportsStore.Properties.Resources.M0006_helmet);
            mImageDictionary.Add("Chess Board", AcmeSportsStore.Properties.Resources.M0007_chess);
        }

        //*==============Part5. "Home" tab ==============*//
        private void btnSportItem_Click(object sender, EventArgs e)
        {
            /*
             * select the 2nd tab
             */
            tabctlMain.SelectedIndex = 1;
        }

        private void btnCustomer_Click(object sender, EventArgs e)
        {
            /*
             * select the 3rd tab
             */
            tabctlMain.SelectedIndex = 2;
        }

          private void btnCustomerAct_Click(object sender, EventArgs e)
        {
            /*
             * select the 4th tab
             */
            tabctlMain.SelectedIndex = 3;
        }

        private void btnMonthlyAct_Click(object sender, EventArgs e)
        {
            /*
             * select the 5th tab
             */
            tabctlMain.SelectedIndex = 4;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            /*
             *close the program
             */
            this.Close();
        }

        //*==================Part6. "Sport Item" tab ==============*//

        private void btnByItemName_Click(object sender, EventArgs e)
        {
            /*
             * set the order type first
             * it will determine how items are loaded into the listbox
             */
            mSportsItemsOrder = SportsItemsOrder.ByName;
            ReloadSportsItems();
        }

        private void btnByItemId_Click(object sender, EventArgs e)
        {
            /*
             * set the order type first
             * it will determine how items are loaded into the listbox
             */
            mSportsItemsOrder = SportsItemsOrder.ById;
            ReloadSportsItems();
        }

        private void ByItemPrice_Click(object sender, EventArgs e)
        {
            /*
             * set the order type first
             * it will determine how items are loaded into the listbox
             */
            mSportsItemsOrder = SportsItemsOrder.ByPrice;
            ReloadSportsItems();
        }

        private void cmbItemID_SelectedIndexChanged(object sender, EventArgs e)
        {
            object selectedItem = this.cmbItemID.SelectedItem;

            if (selectedItem != null && !mNoSelectBack)
            {
                string selText = (string)selectedItem;

                /* this is the index in the ID indexer */
                int index = this.mSportsStore.GetIndexForId(new SportsItem(selText, null, null, 0));

                /*
                 * get the real item in the list
                 */
                SportsItem item = mSportsStore.GetItemByIndexForId(index);

                /* 
                 * this is the index of the real item in the indexer for 
                 * current indexing choice
                 */
                index = GetSportsItemIndex(item);

                mNoSelectBack = true;
                this.lstItems.SelectedIndex = index;
                mNoSelectBack = false;
            }
        }

        private void btnClear_tabSportsItems_Click(object sender, EventArgs e)
        {
            this.lstItems.SelectedIndex = -1;     /* deselect all */
            this.txtItemDetails.Text = "";

            /*
             * set preview image
             */
            this.pbxPreview.Image = null;
        }

        private void btnHome_tabSportsItems_Click(object sender, EventArgs e)
        {
            /*
             * select the 1st tab
             */
            tabctlMain.SelectedIndex = 0;
        }
        private SportsItem GetSportsItemByIndex(int index)
        {
            switch (mSportsItemsOrder)
            {
                case SportsItemsOrder.ById:
                    return mSportsStore.GetItemByIndexForId(index);
                case SportsItemsOrder.ByName:
                    return mSportsStore.GetItemByIndexForName(index);
                case SportsItemsOrder.ByDescription:
                    return mSportsStore.GetItemByIndexForDescription(index);
                case SportsItemsOrder.ByPrice:
                    return mSportsStore.GetItemByIndexForPrice(index);
                default:
                    throw new ApplicationException("Unknown order type");
            }
        }

        private int GetSportsItemIndex(SportsItem item)
        {
            switch (mSportsItemsOrder)
            {
                case SportsItemsOrder.ById:
                    return mSportsStore.GetIndexForId(item);
                case SportsItemsOrder.ByName:
                    return mSportsStore.GetIndexForName(item);
                case SportsItemsOrder.ByDescription:
                    return mSportsStore.GetIndexForDescription(item);
                case SportsItemsOrder.ByPrice:
                    return mSportsStore.GetIndexForPrice(item);
                default:
                    throw new ApplicationException("Unknown order type");
            }
        }

        private void lstItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = lstItems.SelectedIndex;

            if (index < 0)
            {   /* nothing selected */
                txtItemDetails.Clear();
                cmbItemID.SelectedIndex = -1;  /* deselection for combo box */
                return;
            }

            /*
             * get the item from the sports list
             * using the indexer according to indexing mode chosen
             */
            SportsItem item = GetSportsItemByIndex(index);
            string name = item.Name;

            /*
             * <comments>
             *  Set the image for preview
             *  check the existence first
             *  because not every item has got its image
             * </comments>
             */

            if (mImageDictionary.ContainsKey(name))
            {
                pbxPreview.Image = mImageDictionary[name];
            }
            else
            {
                pbxPreview.Image = mDefSportsItemPreview;
            }

            if (!mNoSelectBack)
            {
                mNoSelectBack = true;
                /*
                 * get the index of the item in the ID indexer
                 * which is equal to the index of its corresponding
                 * entry in the combo box
                 */
                index = mSportsStore.GetIndexForId(item);
                cmbItemID.SelectedIndex = index;
                mNoSelectBack = false;
            }

            /*txtItemDetails
             * details
             * we use string builder to concatenate the strings
             */
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("[ID]");
            sb.AppendLine(item.Id);
            sb.AppendLine();
            sb.AppendLine("[Name]");
            sb.AppendLine(item.Name);
            sb.AppendLine();
            sb.AppendLine("[Description]");
            sb.AppendLine(item.Description);
            sb.AppendLine();
            sb.AppendLine("[Price]");
            sb.AppendLine(item.PriceString);
            txtItemDetails.Text = sb.ToString();
        }

        //*===========Part7 "Customer " tab -- codes for the 3rd tab=============*//
        private void cmbCustomerID_SelectedIndexChanged(object sender, EventArgs e)
        {
            object selectedItem = this.cmbCustomerID.SelectedItem;

            if (selectedItem != null && !mNoSelectBack)
            {
                int selText = (int)selectedItem;

                /* this is the index in the ID indexer */
                int index = this.mCustomers.GetIndexForId(new CustomersItem(selText,null,null,null));

                /*
                 * get the real item in the list
                 */
                CustomersItem item = mCustomers.GetItemByIndexerForId(index);
                /* 
                 * this is the index of the real item in the indexer for 
                 * current indexing choice
                 */
                index = GetCustomerIndex(item);

                mNoSelectBack = true;
                this.listCustomers.SelectedIndex = index;
                mNoSelectBack = false;
            }     
        }

        private void btnHomeFromTab2_Click(object sender, EventArgs e)
        {
            /*
             *  go back to the home page
             */
            this.tabctlMain.SelectedIndex = 0;
        }

        private void btnHomeFromTab3_Click(object sender, EventArgs e)
        {
            /*
             *  go back to the home page
             */
            this.tabctlMain.SelectedIndex = 0;
        }

       
        private void SportsView_Resize(object sender, EventArgs e)
        {
            if (mLayoutController != null)
            {
                mLayoutController.UpdateAfterResizing();
            }
        }
        private void btnHome_tabCustomers_Click(object sender, EventArgs e)
        {
            /*
             * select the 1st tab
             */
            tabctlMain.SelectedIndex = 0;
        }

        private int GetCustomerIndex(CustomersItem customer)
        {
            switch (mCustomersOrder)
            {
                case CustomersOrder.ById:
                    return mCustomers.GetIndexForId(customer);
                case CustomersOrder.ByName:
                    return mCustomers.GetIndexForName(customer);
                case CustomersOrder.ByAddress:
                    return mCustomers.GetIndexForAddress(customer);
                case CustomersOrder.ByPhone:
                    return mCustomers.GetIndexForPhone(customer);
                default:
                    throw new ApplicationException("Unknown order type");
            }
        }

        private CustomersItem GetCustomerItemByIndex(int index)
        {
            switch (mCustomersOrder)
            {
                case CustomersOrder.ById:
                    return mCustomers.GetItemByIndexerForId(index);
                case CustomersOrder.ByName:
                    return mCustomers.GetItemByIndexerForName(index);
                case CustomersOrder.ByAddress:
                    return mCustomers.GetItemByIndexerForAddress(index);
                case CustomersOrder.ByPhone:
                    return mCustomers.GetItemByIndexerForPhone(index);
                default:
                    throw new ApplicationException("Unknown order type");
            }
        }

        private void listCustomers_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = listCustomers.SelectedIndex;

            if (index < 0)
            {   /* nothing selected */
                cmbCustomerID.SelectedIndex = -1;  /* deselection in comb-box */
                txtCustomerDetails.Clear();    /*clear the customer details*/
                return;
            }

            CustomersItem item = GetCustomerItemByIndex(index);
            string name = item.CustName;

            if (!mNoSelectBack)
            {
                mNoSelectBack = true;
                /*
                 * get the index of the item in the ID indexer
                 * which is equal to the index of its corresponding
                 * entry in the combo box
                 */
                index = mCustomers.GetIndexForId(item);
                cmbCustomerID.SelectedIndex = index;
                mNoSelectBack = false;
            }
            /*
             * details
             * we use string builder to concatenate the strings
             */
            StringBuilder cb = new StringBuilder();
            cb.AppendLine("[ID]");
            cb.AppendLine(Convert.ToString(item.CustId));
            cb.AppendLine();
            cb.AppendLine("[Name]");
            cb.AppendLine(item.CustName);
            cb.AppendLine();
            cb.AppendLine("[Address]");
            cb.AppendLine(item.CustAddress);
            cb.AppendLine();
            cb.AppendLine("[Phone]");
            cb.AppendLine(item.CustPhone);
            txtCustomerDetails.Text = cb.ToString();
        }

        private void btnById_Click(object sender, EventArgs e)
        {
            /*
           * set the order type first
           * it will determine how items are loaded into the listbox
           */
            mCustomersOrder = CustomersOrder.ById;
            ReloadCustomersItems();
        }

        private void btnByCustName_Click(object sender, EventArgs e)
        {
            mCustomersOrder = CustomersOrder.ByName;
            ReloadCustomersItems();
        }

        private void btnByCustAddress_Click(object sender, EventArgs e)
        {
            mCustomersOrder = CustomersOrder.ByAddress;
            ReloadCustomersItems();
        }

        private void btnClear_tabCustomers_Click(object sender, EventArgs e)
        {
            this.listCustomers.SelectedIndex = -1;     /* deselect all */
            this.txtCustomerDetails.Text = "";
        }

        //*============Part8. "Customer Activity" tab ===========*//
        private void btnHome_tabPCustomerActs_Click(object sender, EventArgs e)
        {
            /*
             * select the 1st tab
             */
            tabctlMain.SelectedIndex = 0;
        }

        private void cmbCustomerID_tabCustActs_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index;
            txtCustomerAct.Text = ""; //Clean the contact

            if (this.cmbCustomerID_tabCustActs.SelectedIndex < 0)
            {
                return;
            }

            /*
             * customer Id in selText
             */
            string selText = Convert.ToString(this.cmbCustomerID_tabCustActs.SelectedItem);
            ArrayList result = new ArrayList();
            StringBuilder cb = new StringBuilder();

            index = this.mCustomers.GetIndexForId(new CustomersItem(Convert.ToInt32(selText), "", "", ""));
            CustomersItem customer = this.mCustomers.GetItemByIndexerForId(index);
            cb.AppendLine("Customer: " + selText);
            cb.Append("Customer Name:\t");
            cb.AppendLine(customer.CustName);
            cb.Append("Address:\t");
            cb.AppendLine(customer.CustAddress);
            cb.Append("Phone Number:\t");
            cb.AppendLine(customer.CustPhone.ToString());
            result.AddRange(mPurchasedStore.GetItemsByCustId(selText));

            if (result.Count > 0)
            {
                cb.AppendLine(" ");
                cb.AppendLine("The customer has the following activitiy(s):");
                cb.AppendLine("------------------------------");
                cb.AppendLine("");

                for (int i = 0; i < result.Count; i++)
                {
                    PurchasedItem pi = (PurchasedItem)result[i];
                    index = this.mSportsStore.GetIndexForId(new SportsItem(pi.ItemId, "", "", 0));
                    SportsItem si = this.mSportsStore.GetItemByIndexForId(index); 
                    cb.AppendLine("Activity Date:\t"+ pi.DeliverDate);
                    cb.AppendLine("\nPurchased Product:");
                    cb.AppendLine("ID:\t" + si.Id);
                    cb.AppendLine("Name:\t" + si.Name);
                    cb.AppendLine("Description:\t" + si.Description);
                    cb.AppendLine("Worth:\t" + pi.Price);
                    cb.AppendLine("------------------------------");
                    cb.AppendLine("");
                }
            }
            else
            {
                cb.AppendLine("The customer has no activity.");
            }
            txtCustomerAct.Text = cb.ToString();
        }

        private void btnClear_tabPCustomerActs_Click(object sender, EventArgs e)
        {
            txtCustomerAct.Text = "";
            cmbCustomerID_tabCustActs.SelectedIndex = -1;   /*deselect on clearing up*/
        }

        //*============Part9. "Monthly Activity" tab ============*//
        private void btnMonAct_home_Click(object sender, EventArgs e)
        {
            /*
             * select the 1st tab
             */
            tabctlMain.SelectedIndex = 0;
        }

        private void cmbItemID_tabMonthlyActs_SelectedIndexChanged(object sender, EventArgs e)
        {
            double totalPrice = 0;
            int index;
            txtMonthlyAct.Text = ""; //Clean the contact

            if (this.cmbItemID_tabMonthlyActs.SelectedIndex < 0)
            {
                return;
            }

            string selText = Convert.ToString(this.cmbItemID_tabMonthlyActs.SelectedItem);
            ArrayList result = new ArrayList();
            StringBuilder sb = new StringBuilder();
            result.AddRange(mPurchasedStore.GetItemsByItemId(selText));

            index = this.mSportsStore.GetIndexForId(new SportsItem(selText, "", "", 0));
            SportsItem si = this.mSportsStore.GetItemByIndexForId(index);
            sb.Append("\nThe Product Id:\t" + si.Id);
            sb.Append("Product Name:\t" + si.Name);
            sb.AppendLine("Description:\t");
            sb.AppendLine(si.Description);
            sb.AppendLine("-----------------------------");
            sb.AppendLine("");

            if (result.Count > 0)
            {
                for (int i = 0; i < result.Count; i++)
                {
                    PurchasedItem pi = (PurchasedItem)result[i];
                    sb.Append("Tanscation " + (i + 1));
                    sb.Append(" :\t" + pi.DeliverDate);
                    sb.Append("\tIncome: $" + pi.Price);
                    totalPrice += Convert.ToDouble(pi.Price);
                }
                sb.AppendLine("------------------------------");
                sb.Append("\nTotal Income from This Product: \t$");
                sb.AppendLine(Convert.ToString(totalPrice));
            }
            else
            {
                sb.AppendLine(" The item has not transaction records.");
            }
            txtMonthlyAct.Text = sb.ToString();
        }

        private void btnMonClear_Click(object sender, EventArgs e)
        {
            txtMonthlyAct.Text = "";
            cmbItemID_tabMonthlyActs.SelectedIndex = -1;  /*deselect on clearing up*/
        }

        //*============Part10. Top Menu Bar =============*//
        private void SetToLogoffState()
        {
            EnableMenuItems(false);
            Login_MenuLog.Enabled = true;
            MenuHelp.Enabled = true;

            statusLabel1.Text = " ";

            ClearDataDisplay();
            // TODO: ....

            // turn to black-white image
            this.pbxIntro.Image = null;
        }

        private void Logoff_MenuLog_Click(object sender, EventArgs e)
        {
            SetToLogoffState();
        }

        private void Exit_MenuLog_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ChPassWord_MenuEdit_Click(object sender, EventArgs e)
        {
            newPasswordForm.ShowDialog(this);
        }

        private void EnableMenuItems(bool enabled)
        {
            this.tabctlMain.Enabled = enabled;
            this.MenuFile.Enabled = enabled;
            this.MenuEdit.Enabled = enabled;
            this.MenuHelp.Enabled = enabled;
            this.Login_MenuLog.Enabled = enabled;
            this.Logoff_MenuLog.Enabled = enabled;
            this.toolStripMenuItem3.Enabled = enabled;
            this.toolStripMenuItem4.Enabled = enabled;
            // load the colored image 
            this.pbxIntro.Image = AcmeSportsStore.Properties.Resources.background;
        }

        private void Admin_MenuLogin_Click(object sender, EventArgs e)
        {
            DialogResult dr = passwordForm.ShowDialog(this);
            string loginName = passwordForm.LoginName;
            if (dr == DialogResult.OK)
            {
                EnableMenuItems(true);
                this.Login_MenuLog.Enabled = false;
                this.statusLabel1.Text = "You've logged in as:\t" + loginName;
                /*
                 * create context for the user
                 */

                if (!string.IsNullOrEmpty(AccountsStore.DataSetFilePath))
                {
                    LoadDatasetFromXml(AccountsStore.DataSetFilePath);
                }
            }
            // in this case, the program just ignores other return values
        }

        private void About_MenuHelp_Click(object sender, EventArgs e)
        {
            AboutBox aboutBox = new AboutBox();
            aboutBox.ShowDialog();
        }

        //*=========Part11. reload items of sports, customers, activities and monthly activities========*//
        private void ReloadSportsItems()
        {
            /*
             * clear the listbox items first
             */
            this.lstItems.Items.Clear();

            /*
             * select the items in specific order
             */
            if (mSportsItemsOrder == SportsItemsOrder.ById)
            {
                for (int i = 0; i < mSportsStore.Count; i++)
                {
                    SportsItem sportsItem = mSportsStore.GetItemByIndexForId(i);
                    this.lstItems.Items.Add(sportsItem.Id + "; " + sportsItem.Name
                        + "; " + sportsItem.PriceString);
                }
            }
            else if (mSportsItemsOrder == SportsItemsOrder.ByName)
            {
                for (int i = 0; i < mSportsStore.Count; i++)
                {
                    SportsItem sportsItem = mSportsStore.GetItemByIndexForName(i);
                    this.lstItems.Items.Add(sportsItem.Id + "; " + sportsItem.Name
                        + "; " + sportsItem.PriceString);
                }
            }
            else if (mSportsItemsOrder == SportsItemsOrder.ByPrice)
            {
                for (int i = 0; i < mSportsStore.Count; i++)
                {
                    SportsItem sportsItem = mSportsStore.GetItemByIndexForPrice(i);
                    this.lstItems.Items.Add(sportsItem.Id + "; " + sportsItem.Name
                        + "; " + sportsItem.PriceString);
                }
            }

            /*
             * set the combo box for id unselected
             */
            cmbItemID.SelectedIndex = -1;
        }

        private void ReloadCustomersItems()
        {
            /*
             * clear the listbox items first
             */
            this.listCustomers.Items.Clear();

            /*
             * select the items in specific order
             */
            if(mCustomersOrder == CustomersOrder.ById )
            {
                for (int i = 0; i < mCustomers.Count; i++)
                {
                    CustomersItem customersItem = mCustomers.GetItemByIndexerForId(i);
                    this.listCustomers.Items.Add(customersItem.CustId + "; " + customersItem.CustName
                        + "; " + customersItem.CustPhone);
                }
            }
            else if (mCustomersOrder == CustomersOrder.ByName )
            {
                for (int i = 0; i < mCustomers.Count; i++)
                {
                    CustomersItem customersItem = mCustomers.GetItemByIndexerForName(i);
                    this.listCustomers.Items.Add(customersItem.CustId + "; " + customersItem.CustName
                        + "; " + customersItem.CustPhone);
                }
            }

            else if (mCustomersOrder == CustomersOrder.ByAddress)
            {
                for (int i = 0; i < mCustomers.Count; i++)
                {
                    CustomersItem customersItem = mCustomers.GetItemByIndexerForAddress(i);
                    this.listCustomers.Items.Add(customersItem.CustId + "; " + customersItem.CustName
                        + "; " + customersItem.CustPhone);
                }
            }

            /*
             * set the combo box for id unselected
             */
            cmbCustomerID.SelectedIndex = -1;
        }
        private void ReloadCustActivities()
        {
            //reset the index value
            cmbCustomerID_tabCustActs.SelectedIndex = -1;
        }

        private void ReloadMonthlyActivities()
        {
            //reset the index value 
            cmbItemID_tabMonthlyActs.SelectedIndex = -1;
        }

        //*============Part12. Load Data set from Xml files ==========*//
        private void LoadDatasetFromXml(string xmlFilePath)
        {
            /*
             * update the current dataset file path of the user account
             */
            AccountsStore.DataSetFilePath = xmlFilePath;

            string xmlDir = Path.GetDirectoryName(xmlFilePath);
            string xmlFileWithoutExt = Path.GetFileNameWithoutExtension(xmlFilePath);

            string dataFileFolder = Path.Combine(xmlDir, xmlFileWithoutExt);

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataFilesInfo));

            try
            {
                using (FileStream fs = new FileStream(xmlFilePath, FileMode.Open))
                {
                    this.mDataFilesInfo = (DataFilesInfo)xmlSerializer.Deserialize(fs);
                }

                string sportsItemsFilePath = Path.Combine(dataFileFolder, 
                    this.mDataFilesInfo.SportsItemsFile);
                string customersFilePath = Path.Combine(dataFileFolder,
                    this.mDataFilesInfo.CustomersFile);
                string purchasedItems = Path.Combine(dataFileFolder,
                    this.mDataFilesInfo.PurchasedItemsFile);

                using (StreamReader srSportsItems = new StreamReader(sportsItemsFilePath))
                using (StreamReader srCustomers = new StreamReader(customersFilePath))
                using (StreamReader srPurchasedItems = new StreamReader(purchasedItems))
                {
                    FileReader fr = new FileReader(srSportsItems, srCustomers, srPurchasedItems);
                    mSportsStore = fr.ReadSportsItems();
                    mCustomers = fr.ReadCustomers();
                    mPurchasedStore = fr.ReadPurchasedItems();
                }

                /*
                 * set the order type first
                 * it will determine how items are loaded into the listbox
                 */
                mSportsItemsOrder = SportsItemsOrder.ById;
                ReloadSportsItems();         // after selecting order type, reload Sportitems to update data
                mCustomersOrder = CustomersOrder.ById;
                ReloadCustomersItems();  // after selecting order type, reload Customers to update data
                ReloadCustActivities();      //reset the data set in "Customer Activity" tab
                ReloadCustomersItems(); // reset the data set in "Monthly Activity" tab
                
                /*
                 * load ids to the combobox
                 */
                for (int i = 0; i < mSportsStore.Count; i++)
                {
                    SportsItem item = mSportsStore.GetItemByIndexForId(i);
                    cmbItemID.Items.Add(item.Id);
                    cmbItemID_tabMonthlyActs.Items.Add(item.Id);
                }

                for (int i = 0; i < mCustomers.Count; i++)
                {
                    CustomersItem cItem = mCustomers.GetItemByIndexerForId(i);
                    cmbCustomerID.Items.Add(cItem.CustId);
                    cmbCustomerID_tabCustActs.Items.Add(cItem.CustId);
                }
            }

            catch (Exception)
            {
                MessageBox.Show("Oops! An error occurred during loading the project file.", this.Text);
                /*
                 * since the loading is not successful
                 * set the dataset file path for the user to null
                 */
                CloseDataset();
            }
        }

        /*
         * load the dataset
         */
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            DialogResult dr = OpenFileDlg.ShowDialog();

            if (dr == DialogResult.OK)
            {
                /*
                 * a file is selected to be opened
                 */
                LoadDatasetFromXml(OpenFileDlg.FileName);
            }
        }

        private void SaveProjectAtSpecificLocation()
        {
            DialogResult dr = SaveFileDlg.ShowDialog();

            string srcXmlFilePath = AccountsStore.DataSetFilePath;

            if (srcXmlFilePath != null && dr == DialogResult.OK)
            {
                string srcXmlDir = Path.GetDirectoryName(srcXmlFilePath);
                string srcXmlFileWithoutExt = Path.GetFileNameWithoutExtension(srcXmlFilePath);

                string srcDataFileFolder = Path.Combine(srcXmlDir, srcXmlFileWithoutExt);

                string srcSportsItemsFilePath = Path.Combine(srcDataFileFolder,
                    this.mDataFilesInfo.SportsItemsFile);
                string srcCustomersFilePath = Path.Combine(srcDataFileFolder,
                    this.mDataFilesInfo.CustomersFile);
                string srcPurchasedItemsPath = Path.Combine(srcDataFileFolder,
                    this.mDataFilesInfo.PurchasedItemsFile);

                string xmlFilePath = SaveFileDlg.FileName;
                string xmlDir = Path.GetDirectoryName(xmlFilePath);
                string xmlFileWithoutExt = Path.GetFileNameWithoutExtension(xmlFilePath);

                /*
                 * update the data set file path
                 */
                AccountsStore.DataSetFilePath = xmlFilePath;

                string dataFileFolder = Path.Combine(xmlDir, xmlFileWithoutExt);
                if (!Directory.Exists(dataFileFolder))
                {
                    DirectoryInfo dirInfo = Directory.CreateDirectory(dataFileFolder);
                }

                /*
                 * a destination file that is specified to be saved to
                 */
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataFilesInfo));

                using (FileStream fs = new FileStream(xmlFilePath, FileMode.Create))
                {
                    xmlSerializer.Serialize(fs, mDataFilesInfo);
                }

                if (string.IsNullOrEmpty(mDataFilesInfo.SportsItemsFile))
                {
                    mDataFilesInfo.SportsItemsFile = "sportsItems.txt";
                }
                if (string.IsNullOrEmpty(mDataFilesInfo.CustomersFile))
                {
                    mDataFilesInfo.CustomersFile = "customersInfo.txt";
                }
                if (string.IsNullOrEmpty(mDataFilesInfo.PurchasedItemsFile))
                {
                    mDataFilesInfo.PurchasedItemsFile = "purchasedItems.txt";
                }

                /* 
                 * in this version we simply copy text data files from the 
                 * source project to the target project.
                 * because data editing and file writing have been 
                 * implemented
                 */
                string sportsItemsTxtPath = Path.Combine(dataFileFolder, mDataFilesInfo.SportsItemsFile);
                string customersTxtPath = Path.Combine(dataFileFolder, mDataFilesInfo.CustomersFile);
                string purchasedItemsTxtPath = Path.Combine(dataFileFolder, mDataFilesInfo.PurchasedItemsFile);

                /*
                 * the folder 'srcDataFileFolder' indicates has already been created
                 */
                File.Copy(srcSportsItemsFilePath, sportsItemsTxtPath);
                File.Copy(srcCustomersFilePath, customersTxtPath);
                File.Copy(srcPurchasedItemsPath, purchasedItemsTxtPath);
            }
        }

        /*
         * save the dataset as ...
         */
        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            SaveProjectAtSpecificLocation();
        }

        private void ClearDataDisplay()
        {
            /*
             * go back to home page after logoff
             */
            tabctlMain.SelectedIndex = 0;

            /*
             * clear up everything
             */
            lstItems.Items.Clear();
            listCustomers.Items.Clear();
            cmbItemID.Items.Clear();
            cmbCustomerID.Items.Clear();
            cmbCustomerID_tabCustActs.Items.Clear();
            txtCustomerAct.Text = "";
            txtCustomerDetails.Text = "";
            txtItemDetails.Text = "";
            txtMonthlyAct.Text = "";
            cmbItemID_tabMonthlyActs.Items.Clear();
            mSportsItemsOrder = SportsItemsOrder.ById;

            /*
             * set default image
             */
            pbxPreview.Image = null;
        }

        private void CloseDataset()
        {
            AccountsStore.DataSetFilePath = null;

            // clear everything on display
            ClearDataDisplay();

            // clear data in indexers
            this.mCustomers.Clear();
            this.mSportsStore.Clear();
            this.mPurchasedStore.Clear();
        }

        /*
         * close the dataset
         */
        private void closeDatasetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseDataset();
        }

    }
}
